<template>
    <page-layout-content class="createFence">
        <div class="createFence-title">新增电子围栏</div>
        <div class="createFence-content">
            <div class="createFence-content-left">
                <a-form :form="form" class="createFence-form">
                    <a-form-item
                            :label-col="formItemLayout.labelCol"
                            :wrapper-col="formItemLayout.wrapperCol"
                            label="围栏名称"
                    >
                        <a-input
                                v-decorator="[
                                  'name',
                                ]"
                                placeholder="请输入围栏名称"
                        />
                    </a-form-item>
                    <a-form-item
                            :label-col="formItemLayout.labelCol"
                            :wrapper-col="formItemLayout.wrapperCol"
                            label="围栏方式"
                    >
                        <a-select
                                v-decorator="['fence']"
                                placeholder="请选择围栏"
                                @change="handleSelectChange"
                        >
                            <a-select-option value="polygon">
                                多边形围栏
                            </a-select-option>
                            <a-select-option value="circular">
                                圆形围栏
                            </a-select-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item
                            :label-col="formItemLayout.labelCol"
                            :wrapper-col="formItemLayout.wrapperCol"
                    >
                    </a-form-item>
                    <div style="text-align: center">
                        <a-space>
                            <a-button style="width: 120px;" @click="goBack">
                                取消
                            </a-button>
                            <a-button style="width: 120px;" :loading="submitLoading" type="primary" @click="submitMap">
                                确定
                            </a-button>
                        </a-space>
                    </div>
                </a-form>
            </div>
            <div class="createFence-content-map">
                <div class="createFence-content-map-tip">
                    {{ showSlider ? '操作说明：鼠标左键单击地图选择中心点，并设置围栏半径' : '操作说明：鼠标左键单击地图选点，形成一个闭环' }}
                </div>
                <mapLoading ref="mapLoading"/>
                <div id="searchMap" style="width: 100%;height: 100%;"></div>
                <input id="tipinput" placeholder="搜索中心点地址或直接点击地图" style="width: 200px"/>
                <transition
                        name="fade"
                        enter-active-class="animated slideInUp"
                        leave-active-class="animated slideOutDown"
                >
                    <div class="createFence-content-map-slider" v-show="showSlider">
                        <p>围栏半径</p>
                        <a-slider :min="1000" :disabled="!circle" :max="10000" :tip-formatter="formatter" :value="circleSlider" @change="circleSliderChange" />
                        <div>
                            <span>1km</span>
                            <span>10km</span>
                        </div>
                    </div>
                </transition>
            </div>
        </div>
    </page-layout-content>
</template>

<script>
    const formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };
    const formTailLayout = {
        labelCol: {span: 0},
        wrapperCol: {span: 12, offset: 0},
    };
    import PageLayoutContent from "../../components/pageLayoutContent";
    import mapLoading from "../../components/mapLoading";
    import {createFence} from "../../services/geofence";
    import AMap from 'AMap'
    export default {
        name: "createFence",
        components: {PageLayoutContent, mapLoading},
        data() {
            return{
                formItemLayout,
                formTailLayout,
                form: this.$form.createForm(this, {}),
                map: null,
                mapAuto: null,
                polygon: null,
                polyEditor: null,
                circle: null,
                circleEditor: null,
                circleSlider: 1000,
                movelnglat: null,
                showSlider: true,
                submitLoading: false,
            }
        },
        created() {
            this.$nextTick(() => {
                this.form.setFieldsValue({fence: "circular"})
            })
        },
        mounted() {
            let that = this;
            this.map = new AMap.Map("searchMap", {
                resizeEnable: true
            });
            var autoOptions = {
                input: "tipinput"
            };
            this.mapAuto =  new AMap.Autocomplete(autoOptions);
            AMap.event.addListener(this.mapAuto, "select", select);//注册监听，当选中某条记录时会触发
            function select(e) {
                that.clearMarkerAndEdit();
                let way = that.form.getFieldValue('fence');
                let center = [e.poi.location.lng, e.poi.location.lat];
                that.movelnglat = e.poi.location;
                if (way === 'circular') {
                    that.setCircular(center);
                } else {
                    that.setDistrict(center);
                }
            }
            this.map.on("complete", () =>{
                this.$refs['mapLoading'] && this.$refs['mapLoading'].hideMapLoading();
            });
            this.map.on('click', e => {
                this.movelnglat = e.lnglat;
                let way = that.form.getFieldValue('fence');
                this.handleSelectChange(way);
            })
        },
        methods:{
            formatter(value) {
                return `${value/1000}km`;
            },
            getDistance(center) {
                let topLeft = [center[0] + 0.005, center[1] - 0.005];
                let topRight = [center[0] - 0.005, center[1] - 0.005];
                let bottomLeft = [center[0] - 0.005, center[1] + 0.005];
                let bottomRight = [center[0] + 0.005, center[1] + 0.005];
                return [
                    topLeft, topRight, bottomLeft, bottomRight
                ]
            },
            setDistrict(center) {
                let pathArr = this.getDistance(center)
                this.polygon = new AMap.Polygon({
                    path: pathArr,
                    strokeColor: "#FF33FF",
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    fillColor: '#1791fc',
                    zIndex: 50,
                    draggable: true
                })
                this.map.add(this.polygon)
                this.polyEditor = new AMap.PolyEditor(this.map, this.polygon);
                this.map.setFitView([ this.polygon ])
                this.polyEditor.open();
                let change = ({lnglat}) => {
                    this.movelnglat = lnglat;
                    this.map.setFitView([ this.polygon ])
                }
                this.polyEditor.on('adjust', change)
                this.polygon.on('dragging', change)
            },
            setCircular(center) {
                let that = this;
                that.circle = new AMap.Circle({
                    center,
                    radius: that.circleSlider, //半径
                    borderWeight: 3,
                    strokeColor: "#FF33FF",
                    strokeWeight: 6,
                    strokeOpacity: 0.2,
                    fillOpacity: 0.4,
                    strokeStyle: 'dashed',
                    strokeDasharray: [10, 10],
                    // 线样式还支持 'dashed'
                    fillColor: '#1791fc',
                    zIndex: 50,
                })
                that.circle.setMap(that.map)
                // 缩放地图到合适的视野级别
                that.map.setFitView([ that.circle ])
                that.circleEditor = new AMap.CircleEditor(that.map, that.circle);
                that.circleEditor.open();
                that.circleEditor.on('adjust', function() {
                    that.map.setFitView([ that.circle ])
                })
                that.circleEditor.on('move', function (e) {
                    that.movelnglat = e.lnglat;
                    that.map.setFitView([ that.circle ])
                })
            },
            handleSelectChange(value) {
                this.showSlider = value !== 'polygon';
                this.clearMarkerAndEdit();
                if (value === 'circular' && (this.movelnglat || this.circle)) {
                    let {lat, lng} = this.movelnglat || this.circle.w.center;
                    this.setCircular([lng, lat]);
                } else if (value === 'polygon' && (this.circle || this.movelnglat)){
                    let {lat, lng} = this.movelnglat || this.circle.w.center;
                    this.setDistrict([lng, lat]);
                }
            },
            circleSliderChange(value) {
                this.circleSlider = value;
                this.circle.setRadius(value);
                this.map.setFitView([ this.circle ])
            },
            clearMarkerAndEdit() {
                this.polygon && this.map.remove(this.polygon);
                this.circle && this.map.remove(this.circle);
                this.circleEditor && this.circleEditor.close();
                this.polyEditor && this.polyEditor.close();
            },
            goBack() {
                this.$router.push('/system/parameters');
            },
            submitMap() {
                let {name, fence} = this.form.getFieldsValue(),
                    fenceMap = this.showSlider ? this.circle : this.polygon,
                    data = {
                        name,
                        "repeat": "Mon,Tues,Wed,Thur,Fri,Sat,Sun",
                        // "valid_time": "2054-01-01",
                        // "time": "00:00,11:59;13:00,20:59",
                        // "desc": "暂无描述",
                        // "alert_condition": "enter;leave"
                    };
                if (!name) {
                    this.$message.warning('请输入围栏名称');
                    return;
                }
                if (fenceMap === null) {
                    this.$message.warning('请先绘制电子围栏');
                    return;
                }
                this.submitLoading = true;
                if (fence === 'circular') {
                    data.center = [this.movelnglat.lng, this.movelnglat.lat].join(',');
                    data.radius = this.circleSlider.toString();
                } else{
                    let points = this.polygon.getPath().map(({lng, lat}) => {
                        return `${lng},${lat}`
                    }).join(';')
                    data.points = points
                }
                createFence(data).then(({data}) => {
                    let {data:response} = data;
                    if (response.status == '0') {
                        this.$message.success('设置成功');
                        this.submitLoading = false;
                        setTimeout(() => {
                            this.goBack();
                        }, 500)
                    } else {
                        this.$message.warning(response.message);
                        this.submitLoading = false;
                    }
                })
            }
        }
    }
</script>

<style lang="less">
    .createFence{
        display: flex;
        flex-direction: column;
        overflow: hidden;
        &-form{
            margin: 20px 0;
        }
        &-title{
            color: rgba(80, 80, 80, 1);
            font-size: 16px;
            padding: 20px 30px;
            border-bottom: 1px #e5e5e5 solid;
        }
        &-content{
            flex: 1;
            display: flex;
            &-left{
                width: 300px;
            }
            &-map{
                flex: 1;
                height: inherit;
                background: #2c9af2;
                position: relative;
                overflow: hidden;
                &-tip{
                    position: absolute;
                    top: 0;
                    left: 0;
                    right: 0;
                    height: 30px;
                    text-indent: 14px;
                    color: rgba(255, 255, 255, 1);
                    background-color: rgba(0, 0, 0, 0.4);
                    font-size: 14px;
                    z-index: 2;
                    line-height: 30px;
                }
                #tipinput{
                    position: absolute;
                    left: 10px;
                    top: 45px;
                    z-index: 9;
                    width: 262px;
                    height: 30px;
                    text-indent: 5px;
                    color: #333;
                    &::placeholder{
                        color: rgba(153, 153, 153, 1);
                    }
                    background-color: rgba(255, 255, 255, 1);
                    border-radius: 2px;
                    font-size: 12px;
                    line-height: 150%;
                    border: rgba(204, 204, 204, 1) solid 1px;
                    text-align: left;
                }
                &-slider{
                    width: 100%;
                    background: rgba(255, 255, 255, 0.63);
                    position: absolute;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    padding: 10px 15px;
                    transition:all linear .3s ;
                    &:hover{
                        background: #fff;
                        box-shadow: 0px 1px 10px #929292;
                    }
                    p{
                        margin: 0;
                        padding: 0;
                        font-size: 12px;
                    }
                    div{
                        display: flex;
                        justify-content: space-between;
                        font-size: 12px;
                    }
                }
            }
        }
    }
</style>
